package com.example.yblin.hello24.DataUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * NetUtil.java
 * Version:1.0
 */

/**
 * NetUtil：访问服务器专用类。
 * 使用方法：new实例，设置地址和参数，获取数据。
 * 只负责一层json解析
 */
public class NetUtil {
    public static final String ADDR_LOGIN = "http://120.78.129.48/jm24/login.php";
    public static final String ADDR_RANKLIST = "http://120.78.129.48/jm24/ranklist.php";
    public static final String ADDR_START = "http://120.78.129.48/jm24/start.php";
    public static final String ADDR_END = "http://120.78.129.48/jm24/end.php";
    public static final String ADDR_REGISTER = "http://120.78.129.48/jm24/register.php";
    public static final String ADDR_STAGE_START = "http://120.78.129.48/jm24/stagestart.php";
    public static final String ADDR_STAGE_RANKLIST = "http://120.78.129.48/jm24/stageranklist.php";
    public static final String ADDR_STAGE_END = "http://120.78.129.48/jm24/stageend.php";

    public static final int CODE_OK = 200;
    public static final int CODE_CONNECTION_ERROR = -1;
    public static final int CODE_USERNAME_OR_PASSWORD_ERROR = 1;

    public static final String TAG = "NetUtil";

    private Map<String, String> datalist;
    private String addr;
    private Map<String, String> jsonlist;

    public NetUtil(String addr, @Nullable Map<String, String> datalist) {
        this.addr = addr;
        this.datalist = datalist;

    }

    public void setDatalist(Map<String, String> datalist) {
        this.datalist = datalist;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }


    /**
     * @return Map<String, String>
     * @throws IOException
     */
    public Map<String, String> getData() {
        //初始化
        try {
            URL url = new URL(addr);
            Log.i("访问网址：", addr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);


            //准备参数列表
            String strData = "";
            if (datalist != null) {
                for (Map.Entry entry : datalist.entrySet()) {
                    strData += ('&'
                            + URLEncoder.encode((String) entry.getKey(), "UTF-8")
                            + '='
                            + URLEncoder.encode((String) entry.getValue(), "UTF-8"));
                }
                strData = strData.substring(1);
                Log.i(TAG, "参数列表字符串：" + strData);
            } else {
                Log.i(TAG, "参数列表字符串：无");
            }

            //发送数据
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(strData.getBytes());
            os.flush();
            os.close();
            //接受数据
            String strInput = "";
            if (conn.getResponseCode() == CODE_OK) {
                InputStream is = conn.getInputStream();
                Scanner scanner = new Scanner(is);
                scanner.useDelimiter("\\A");

                boolean hasInput = scanner.hasNext();
                if (hasInput) {
                    strInput = scanner.next();
                } else {
                    strInput = "";
                }
            }
            Log.i(TAG, "原始数据：" + strInput);
            //解析数据为Map
            jsonlist = JsonUtil.analyze(strInput);
            if (jsonlist.isEmpty()) {
                jsonlist.put("code", "" + CODE_CONNECTION_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            jsonlist = new LinkedHashMap<>();
            jsonlist.put("code", "" + CODE_CONNECTION_ERROR);
        }

        return jsonlist;
    }


    public static Boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null) {
                return info.isConnected();
            }
        }
        return false;
    }

}
